package cc.hotice.generator.element;

import cc.hotice.generator.consts.MyMapperConst;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

import java.util.List;

/**
 * @author dalston.cheng
 * @version v1.0
 * @date 2021/6/26 01:53
 */
public class SelectListWithConditionElementGenerator extends
        AbstractXmlElementGenerator {

    public SelectListWithConditionElementGenerator() {
        super();
    }

    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$

        answer.addAttribute(new Attribute(
                "id", MyMapperConst.SELECT_LIST_WITH_CONDITION)); //$NON-NLS-1$
        answer.addAttribute(new Attribute("resultMap", //$NON-NLS-1$
                introspectedTable.getBaseResultMapId()));

        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
                "java.lang.Object"));

        context.getCommentGenerator().addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("select "); //$NON-NLS-1$

        answer.addElement(new TextElement(sb.toString()));
        answer.addElement(getBaseColumnListElement());

        sb.setLength(0);
        sb.append("from "); //$NON-NLS-1$
        sb.append(introspectedTable
                .getAliasedFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        answer.addElement(new XmlElement("where"));

        List<IntrospectedColumn> primaryKeyColumns = introspectedTable
                .getPrimaryKeyColumns();
        if (primaryKeyColumns != null && !primaryKeyColumns.isEmpty()) {
            IntrospectedColumn primaryKeyColumn = primaryKeyColumns.get(0);

            sb.setLength(0);
            sb.append("order by "); //$NON-NLS-1$
            sb.append(MyBatis3FormattingUtilities
                    .getAliasedEscapedColumnName(primaryKeyColumn));
            answer.addElement(new TextElement(sb.toString()));
        }

        if (context.getPlugins().sqlMapSelectAllElementGenerated(
                answer, introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}
